﻿using laohan.Common.APIInter;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace laohan.Common.json
{
    /// <summary>
    /// 
    /// </summary>
    public class NTJsonHelper : IJson
    {
        /// <summary>
        /// 对象序列化称json字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public string Serialize<T>(T t)
        {
            try
            {
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };

                return JsonConvert.SerializeObject(t, Formatting.Indented, timeConverter);
            }
            catch (Exception ex)
            {
                throw new Exception("对象序列化成json字符串发生错误，错误原因：" + ex.Message);
            }
        }

        /// <summary>
        /// 对象序列化称json字符串
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        public string Serialize(object t)
        {
            try
            {
                IsoDateTimeConverter timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };

                return JsonConvert.SerializeObject(t, Formatting.Indented, timeConverter);
            }
            catch (Exception ex)
            {
                throw new Exception("对象序列化成json字符串发生错误，错误原因：" + ex.Message);
            }
        }

        /// <summary>
        /// 字符串反序列化成对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="json"></param>
        /// <returns></returns>
        public T Deserialize<T>(string json)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch (Exception ex)
            {
                throw new Exception("字符串反序列化成对象发生错误，错误原因：" + ex.Message);
            }
        }
    }
}
